import type { FormInstance } from 'element-plus'
import type { SystemUserOptionsPropsType, ValuesType } from './typings'
import type { patrolBodyEnum } from '~/store/oam/tour/typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElButton,
  ElIcon,
  ElForm,
  ElRow,
  ElCol,
  ElFormItem,
  ElInput,
  ElDatePicker,
  ElSelect,
  ElOption,
  ElMessage,
  ElSpace,
  ElInputNumber
} from 'element-plus'
import { EditPen } from '@element-plus/icons-vue'
import { GUTTER, SPAN_STYLE_DOUBLE } from '~/utils/const'

import useVuexGetters from '~/hooks/useVuexGetters'
import styles from '../../index.module.scss'

export default defineComponent({
  props: ['visible', 'type', 'record'],
  emits: ['cancel'],
  setup(props: SystemUserOptionsPropsType, { emit }) {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>()
    const formValues = reactive<ValuesType>({})
    const tourState = useVuexGetters('tour', ['patrolBodyOpt'])
    const title = { add: '新增', update: '编辑', read: '查看' }
    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }
    // 提交表单
    const handleSubmitForm = () => {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validate(async (valid) => {
        if (!valid) return
        const params = {
          id: formValues.id,
          cycle: Number(formValues.cycle),
          firstMakeDate: formValues.firstMakeDate
        }
        // 'tour/GetPatrolConfigAddList' 新增接口
        const res = await store.dispatch(
          formValues.firstMakeDate === ''
            ? 'tour/GetPatrolConfigUpdateList'
            : 'tour/GetPatrolConfigUpdateList',
          params
        )
        if (res?.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          handleCloseModal()
        }
      })
    }

    onMounted(() => {
      store.dispatch('tour/GetPatrolModule')

      const { type } = props
      Object.assign(
        formValues,
        type === 'update'
          ? {
              id: props.record?.id,
              typeName: props.record?.typeName,
              moduleName: props.record?.moduleName,
              cycle: props.record?.cycle,
              firstMakeDate: props.record?.firstMakeDate
            }
          : props.record
      )
    })

    return () => {
      const { type, visible } = props
      return (
        <ElDialog
          width="800px"
          title={(title[type] as string) || '查看'}
          modelValue={visible}
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={handleCloseModal}
          v-slots={
            type !== 'read' && {
              footer: () => (
                <>
                  <ElButton type="primary" onClick={handleSubmitForm}>
                    <ElIcon>
                      <EditPen />
                    </ElIcon>
                    &nbsp; {type === 'add' ? '保存' : '修改'}
                  </ElButton>
                  <ElButton onClick={handleCloseModal}>取消</ElButton>
                </>
              )
            }
          }
        >
          <ElForm
            label-width="120px"
            labelPosition="right"
            ref={ruleFormRef}
            class={styles['basicInformation-same-width']}
            model={formValues}
          >
            <ElRow gutter={GUTTER}>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="typeName"
                  label="巡视类型"
                  rules={[{ required: true, message: '请输入巡视类型' }]}
                >
                  {type === 'read' ? (
                    formValues.typeName
                  ) : (
                    <ElInput v-model={formValues.typeName} placeholder="请输入巡视类型" disabled />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="moduleName"
                  label="巡视主体"
                  rules={[{ required: true, message: '请选择巡视主体' }]}
                >
                  <ElSelect v-model={formValues.moduleName} disabled placeholder="请选择巡视主体">
                    {tourState.patrolBodyOpt?.value?.map((item: patrolBodyEnum) => (
                      <ElOption
                        key={item?.typeName}
                        label={item?.typeName}
                        value={item?.typeName}
                      />
                    ))}
                  </ElSelect>
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="cycle"
                  label="巡视生成周期"
                  rules={[{ required: true, message: '请输入巡视生成周期' }]}
                >
                  <ElSpace>
                    <ElInputNumber
                      v-model={formValues.cycle}
                      min={1}
                      max={12}
                      controls-position="right"
                      placeholder="请输入巡视生成周期"
                    />
                    <span>个月</span>
                  </ElSpace>
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="firstMakeDate"
                  label="巡视生成时间"
                  rules={[{ required: true, message: '请输入巡视生成时间' }]}
                >
                  <ElDatePicker
                    v-model={formValues.firstMakeDate}
                    placeholder="请输入巡视生成时间"
                    valueFormat="YYYY-MM-DD"
                    disabled={formValues.firstMakeDate !== null}
                  />
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElForm>
        </ElDialog>
      )
    }
  }
})
